package com.cheetah.protocol.codec;

import com.cheetah.constants.ProtocolConstants;
import com.cheetah.exceptions.CheetahException;
import com.cheetah.protocol.CheetahMessage;
import com.cheetah.protocol.Heartbeat;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.ReferenceCountUtil;


/**
 * @Description:
 *   编码器
 *
 *   协议
 * |==============================|
 * |    协议魔数  |      data       |
 * |    short   |      byte[]     |
 * |<--2 bytes-->|<----4 bytes--->|
 * |==============================|
 */
public class CheetahHeartbeatEncoder extends MessageToByteEncoder<Heartbeat> {


    @Override
    protected void encode(ChannelHandlerContext ctx, Heartbeat heartbeat, ByteBuf out) throws Exception {
        ByteBuf buffer = ctx.alloc().buffer();
        try {

            buffer.writeShort(ProtocolConstants.PROTOCOL_MAGIC_HEARTBEAT);
            buffer.writeBytes(heartbeat.getCmd().getBytes());
            out.writeBytes(buffer);

        }catch (Throwable t){
            throw new CheetahException(t.getMessage(),t);
        }finally {
            ReferenceCountUtil.release(buffer);
        }
    }
}
